<?php
require_once('php/lib/object.php');
require_once('php/lib/functions.php');

/**
 * Object with automatic configuration support.
 *
 * The object will automatically read configuration file for each base class.
 * The configuration settings will be stored in the object variable 'config'.
 *
 * @package lib
 * @author Pascal de Vink
 */
class ConfiguredObject extends Object {
	
	/**
	 * Object settings.
	 *
	 * @var array
	 * @access public
	 */
	var $config = array();
	
	/**
	 * Constructs new instance.
	 */
	function __construct() {
		parent::__construct();
		$this->__configure();
	}
	
	/**
	 * Reads configuration settings.
	 *
	 * @access private
	 */
	function __configure() {
		global $__CONFIG__;

		for ($class = strtolower(get_class($this)); $class && $class != 'cobject'; $class = strtolower(get_parent_class($class))) {
			if (!isset($__CONFIG__[$class])) continue;

			$config_names = $__CONFIG__[$class];
			foreach (explode(',', $config_names) as $config_name) {		
				$config_path = 'php/config/' . trim($config_name) . '.php';
				if (include_exists($config_path)) include($config_path);
			}
		}	
	}
	
	/**
	 * Returns configuration setting or default value if not set.
	 *
	 * @param string $name Name of configuration setting
	 * @param mixed $default Default value if setting not defined (defaults to NULL).
	 * @return mixed Value of configuration setting or default if not defined.
	 */ 
	function config($name, $default = NULL) {
		return isset($this->config[$name])? $this->config[$name] : $default;
	}	
}

/**
 * Registers configuration for class.
 *
 * Note: we had to introduce this because get_class returns lowercase name. 
 *       Then str_add_lowercase() function doesn't work ...
 *
 * @param string $name Name of class.
 * @param string $files Names of configuration files seperated by comma.
 */
function config($name, $files) {
	global $__CONFIG__;
	$__CONFIG__[strtolower($name)] = $files;
}
?>